﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace sunsetmp
{
    public partial class LoginWindow : Form
    {
        private string acces_url = "https://oauth.vk.com/authorize?client_id=3466042&redirect_uri=http://oauth.vk.com/blank.html&scope=audio,wall,friends,groups&display=popup&response_type=token";
        string logout_url = "http://api.vk.com/oauth/logout";
        Core core;

        public LoginWindow(Core c)
        {
            InitializeComponent();
            core = c;
        }

        public string[] HTTP_Parse(string page_data)
        {
            int first_mask = page_data.IndexOf("access_token=") + 13;
            page_data = page_data.Remove(0, first_mask);
            int end_mask = page_data.IndexOf('&');
            string[] data = new string[2];
            data[1] = (page_data.Remove(end_mask, page_data.Length - end_mask));
            first_mask = page_data.IndexOf("user_id=") + 8;
            data[0] = (page_data.Remove(0, first_mask));
            return data;
        }

        public void Logout()
        {
            webBrowser1.Navigate(logout_url);
            webBrowser1.ScriptErrorsSuppressed = true;
        }

        public void Autoriz()
        {
            webBrowser1.Navigate("www.vk.com");
            this.Show();
            webBrowser1.Navigate(acces_url);
            webBrowser1.ScriptErrorsSuppressed = true;
        }

        private void webBrowser1_Navigated_1(object sender, WebBrowserNavigatedEventArgs e)
        {
            webBrowser1.Document.Focus();
            if (e.Url.ToString().IndexOf("access_token=") > 0)
            {
                webBrowser1.Document.Body.Focus();
                string[] data = HTTP_Parse(e.Url.ToString());
                this.Close();
                core.SetAuData(data[0], data[1]);
            }
            else if (e.Url.ToString().IndexOf("error") > 0)
            {
                MessageBox.Show("Ошибка при подключении");
                this.Close();
            }
        }

        private void webBrowser1_NewWindow(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }

        private void webBrowser1_ControlAdded(object sender, ControlEventArgs e)
        {
            e.Control.ToString();

        }
    }
}
